﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrystalDecisions.Web;
using CrystalDecisions.ReportSource;
using System.Data;
using BOAcademias;
using TOAcademias;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

public partial class TunkiFiles_Reportes_VisorReporte : System.Web.UI.Page
{
    BOReporte boReporte = new BOReporte();
    BOPeriodo boPeriodo = new BOPeriodo();
 
    protected void Page_Load(object sender, EventArgs e)
    {
        CrystalReportSource rep=new CrystalReportSource();
        DataTable dt=new DataTable();

        //Recuperar valores del formulario de reporte
        //Genericos
        String reporte = Request.Form["ctl00$ContentPlaceHolder1$reporte"];
        String formato = Request.Form["ctl00$ContentPlaceHolder1$rbFormato"];       
        String academia = Request.Form["ctl00$ContentPlaceHolder1$cboAcademia"];
        
        //Historico y Cierre
        String anio = Request.Form["ctl00$ContentPlaceHolder1$cboAnio"];
        String ciclo = Request.Form["ctl00$ContentPlaceHolder1$cboCiclo"];
        
        //Requerimientos
        String instructor = Request.Form["ctl00$ContentPlaceHolder1$cboInstructor"];
        String seccion = Request.Form["ctl00$ContentPlaceHolder1$cboSeccion"];
        

        String RutaReporte = String.Empty;
        String filtroAcademia = String.Empty;
        String filtroAnio = String.Empty;
        String filtroCiclo = String.Empty;
        String filtroInstructor = String.Empty;
        String filtroSeccion = String.Empty;
        String filtroPeriodoActivo = String.Empty;
        String filtroTotal = String.Empty;

        if (reporte != null)
        {
            Session["Reporte"] = reporte;
        }        
        if (formato != null && Session["Reporte"]!="Requerimiento")
        {
            Session["TipoReporte"] = formato;
        }

        #region Filtro Academia

        if (academia!=null && academia!="[Todos]") {
            Session["Academia"] = academia;
        }
        if (Session["Academia"] != null)
        {
            switch (Session["Reporte"].ToString())
            {
                case "Historico":
                    filtroAcademia = "{SP_REP_HISTORICO_ACADEMIA;1.COD_ACADEMIA}='" + Session["Academia"] + "'";
                    break;
                case "Requerimiento":
                    filtroAcademia = "{SP_REP_REQUERIMIENTO_SECCION;1.COD_ACADEMIA}='" + Session["Academia"] + "'";
                    break;
                case "Cierre":
                    filtroAcademia = "{SP_REP_CIERRE_CURSO;1.COD_ACADEMIA}='" + Session["Academia"] + "'";
                    break;                
            }
            
        }

        #endregion


        #region Filtro Anio

        if (anio != null && anio != "[Todos]")
        {
            Session["Anio"] = anio;
        }
        if (Session["Anio"] != null)
        {
            filtroAnio = "DatePart('YYYY',{SP_REP_HISTORICO_ACADEMIA;1.FEC_INICIO})=" + Session["Anio"];
        }

        #endregion


        #region Filtro Ciclo

        if (ciclo != null && ciclo != "[Todos]")
        {
            Session["Ciclo"] = ciclo;
        }
        if (Session["Ciclo"] != null)
        {
            filtroCiclo = "{SP_REP_HISTORICO_ACADEMIA;1.CICLO}="+ (Convert.ToInt32(Session["Ciclo"])).ToString();
        }

        #endregion


        #region Filtro Instructor

        if (instructor != null && instructor != "[Todos]")
        {
            Session["Instructor"] = instructor;
        }
        if (Session["Instructor"] != null)
        {
            filtroInstructor = "{SP_REP_REQUERIMIENTO_SECCION;1.COD_INSTRUCTOR}='" + Session["Instructor"].ToString()+"'";
        }

        #endregion


        #region Filtro Seccion

        if (seccion != null && seccion != "[Todos]")
        {
            Session["Seccion"] = seccion;
        }
        if (Session["Seccion"] != null)
        {
            filtroSeccion = "{SP_REP_REQUERIMIENTO_SECCION;1.COD_SECCION}='" + Session["Seccion"].ToString()+"'";
        }

        #endregion


        #region Periodo Activo
        if (Session["Reporte"].ToString() == "Requerimiento")
        {            
            filtroPeriodoActivo = "{SP_REP_REQUERIMIENTO_SECCION;1.COD_PERIODO}='" + boPeriodo.obtenerPeriodoActivo().Codigo + "'";
        }
        #endregion


        #region Anidando filtros

        if (filtroAcademia != "") filtroTotal = filtroAcademia;
        if (filtroAnio != "")
        {
            if (filtroTotal != "")
                filtroTotal += " and " + filtroAnio;
            else
                filtroTotal = filtroAnio;
        }
        if (filtroCiclo != "")
        {
            if (filtroTotal != "")
                filtroTotal += " and " + filtroCiclo;
            else
                filtroTotal = filtroCiclo;
        }
        if (filtroInstructor != "")
        {
            if (filtroTotal != "")
                filtroTotal += " and " + filtroInstructor;
            else
                filtroTotal = filtroInstructor;
        }
        if (filtroSeccion != "")
        {
            if (filtroTotal != "")
                filtroTotal += " and " + filtroSeccion;
            else
                filtroTotal = filtroSeccion;
        }
        if (filtroPeriodoActivo != "")
        {
            if (filtroTotal != "")
                filtroTotal += " and " + filtroPeriodoActivo;
            else
                filtroTotal = filtroPeriodoActivo;
        }
        #endregion

        DataSet ds = new DataSet();
        if (Session["Reporte"] == null) Session["Reporte"] = "";
        switch (Session["Reporte"].ToString()) {
            case "Historico":
                ds.Tables.Add(boReporte.reporteHistoricoAcademias());
                if (Session["TipoReporte"].ToString() == "Resumido")
                {
                    RutaReporte = Server.MapPath("ReporteHistoricoAcademia.rpt");
                }
                else
                {
                    RutaReporte = Server.MapPath("ReporteHistoricoAcademiaDeta.rpt");
                }
                break;
            case "Requerimiento":
                ds.Tables.Add(boReporte.reporteRequerimientoxSeccion());
                RutaReporte = Server.MapPath("ReporteRequerimientoxSeccion.rpt");
                break;
        }

        //Obtener el nombre del servidor del archivo DBModuloAcademias.dbml
        //String Servidor = boReporte.ParametrosConexion().ElementAt(0);
        //String BD = boReporte.ParametrosConexion().ElementAt(1);

        rep.ReportDocument.FileName = RutaReporte;
        rep.ReportDocument.SetDataSource(ds);

        //AsignarConexion(RutaReporte,
        //                rep.ReportDocument,
        //                "", "", true,
        //                Servidor,BD);

        crvReporte.ReportSource = rep;
        crvReporte.SelectionFormula = filtroTotal;        
        //crvReporte.DisplayGroupTree = false;
        crvReporte.BestFitPage = false;
        crvReporte.Height = 1150;
        crvReporte.Width = 900;
        crvReporte.PrintMode = CrystalDecisions.Web.PrintMode.ActiveX;
        crvReporte.RefreshReport();

    }

    public void AsignarConexion(String FileReport, ReportDocument Reporte, String Username, String Password, Boolean SeguridadIntegrada, String Servername, String BD) //Implements IPrintReport.PrintLogon
    {
        Boolean IsConnecting = true;
        ReportDocument crNicasoftStandarReport = new ReportDocument();

        Sections crSections;
        ReportObjects crReportObjects;
        SubreportObject crSubreportObject;
        ReportDocument crSubreportDocument;

        Database crDatabase;
        Tables crTables;
        TableLogOnInfo crTableLogOnInfo;
        ConnectionInfo crConnectioninfo;

        while (IsConnecting)
        {
            try
            {
                crConnectioninfo = new ConnectionInfo();
                crConnectioninfo.ServerName = Servername;
                crConnectioninfo.DatabaseName = BD;
                //crConnectioninfo.UserID = Username;
                //crConnectioninfo.Password = Password;
                crConnectioninfo.IntegratedSecurity = SeguridadIntegrada;                

                crNicasoftStandarReport.Load(FileReport);

                crDatabase = Reporte.Database;
                crTables = crDatabase.Tables;

                foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in crTables)
                {
                    crTableLogOnInfo = crTable.LogOnInfo;
                    crTableLogOnInfo.ConnectionInfo = crConnectioninfo;
                    crTable.ApplyLogOnInfo(crTableLogOnInfo);
                }

                crSections = Reporte.ReportDefinition.Sections;

                foreach (Section crSection in crSections)
                {
                    crReportObjects = crSection.ReportObjects;

                    foreach (ReportObject crReportObject in crReportObjects)
                    {
                        if (crReportObject.Kind == ReportObjectKind.SubreportObject)
                        {

                            crSubreportObject = (SubreportObject)crReportObject;

                            crSubreportDocument = crSubreportObject.OpenSubreport(crSubreportObject.SubreportName);

                            crDatabase = crSubreportDocument.Database;
                            crTables = crDatabase.Tables;

                            foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in crTables)
                            {
                                crConnectioninfo.ServerName = Servername;
                                crConnectioninfo.DatabaseName = BD;
                                //crConnectioninfo.UserID = Username;
                                //crConnectioninfo.Password = Password;
                                crConnectioninfo.IntegratedSecurity = true;

                                crTableLogOnInfo = crTable.LogOnInfo;
                                crTableLogOnInfo.ConnectionInfo = crConnectioninfo;
                                crTable.ApplyLogOnInfo(crTableLogOnInfo);
                            }
                        }
                    }
                }

                crvReporte.ReportSource = Reporte;
                IsConnecting = false;

            }
            catch (Exception ex) { }

        }
    }


}
